import { Select, Tag, theme } from "antd";
import { useRequest } from "ahooks";
import { evaluationV1ControllerIndex } from "@/services/auto/evaluation";
import { Fragment, useEffect, useRef } from "react";
import { evaluationComposeV1ControllerIndex } from "@/services/auto/evaluationCompose";
import { EvaluationCategory } from "common/utils/data";
import Highlighter from "react-highlight-words";

export default function EvaluationAndComposeSelect({
  value,
  onChange,
                                         }:{
    value?: Value;
    onChange?: (val?: Value)=>void;
}){
  const { token } = theme.useToken();

    const {data: evaluationData ,loading: evaluationLoading ,runAsync: evaluationRun } = useRequest((param: Partial< API.EvaluationIndexDto>)=>{
      return evaluationV1ControllerIndex({orderBy: 'updateTime', direction: 'DESC', ...param})
    }, {
      manual: true,
      debounceWait: 300,
    });

    const {data: evaluationComposeData ,loading: evaluationComposeLoading ,runAsync: evaluationComposeRun } = useRequest((param: Partial<API.EvaluationComposeV1ControllerIndexParams>)=>{
      return evaluationComposeV1ControllerIndex({orderBy: 'updateTime', direction: 'DESC', ...param})
    }, {
      manual: true,
      debounceWait: 300,
    });

    const searchValueRef = useRef<string>();

    const onChangingRef = useRef<boolean>(false);

    const search = (param: {
      keyword?: string;
      uuids?: string;
    })=>{
      evaluationRun(param)
      evaluationComposeRun({
        ...param,
      })
    }

    useEffect(() => {
      if(value?.uuid){
        if(!searchValueRef.current && !onChangingRef.current){
          search({
            uuids: value.uuid,
          })
        }
      }else{
        search({})
      }
      onChangingRef.current = false;
    }, [value?.uuid]);


  const evaluationDataEarbudsList = evaluationData?.list.filter(item=>item.category === EvaluationCategory.EARBUDS);
  const evaluationDataSoundSourceList = evaluationData?.list.filter(item=>item.category === EvaluationCategory.SOUND_SOURCE);
    return <Select
      allowClear
      onChange={(value)=>{
        onChangingRef.current = true;
        if(evaluationComposeData?.list.some(item=>item.uuid)){
          onChange?.({
            uuid: value,
            type: 'compose'
          })
        }else{
          const evaluation =  evaluationData?.list.find(item=>item.uuid)!;
          onChange?.({
            uuid: value,
            type: ({
              [EvaluationCategory.EARBUDS]: 'earbuds',
              [EvaluationCategory.SOUND_SOURCE]: 'soundSource',
            })[evaluation.category] as ValueType
          })
        }

      }}
      filterOption={false}
      value={value?.uuid}
      placeholder="请输入数据、品牌关键字进行搜索，最多展示匹配的20条"
      loading={evaluationLoading || evaluationComposeLoading}
      showSearch
      onSearch={(val)=>{
        searchValueRef.current = val;
        evaluationRun({
          keyword: val,
        })
        evaluationComposeRun({
          keyword: val,
        })
      }}
      options={[
        {
          label: `我的HiFi系统${evaluationComposeData?.list.length ? '' : ' 无匹配数据'}`,
          title: '我的HiFi系统',
          options: evaluationComposeData?.list.map(item=>{
            return {
              label: item.title,
              value: item.uuid,
            }
          }),
        },
        {
          label: `耳机${evaluationDataEarbudsList?.length ? '' : ' 无匹配数据'}`,
          title: '耳机',
          options: evaluationDataEarbudsList?.map(item=>{
            return {
              label: <Fragment>
              <Tag color="volcano" bordered={false}>{item.brand.title}</Tag>
              <Highlighter
                highlightStyle={{
                  color: token.colorError,
                }}
                highlightTag="span"
                searchWords={[searchValueRef.current!]}
                textToHighlight={item.title}
              />
              </Fragment>,
              value: item.uuid,
            }
          }),
        },
        {
          label: `音源${evaluationDataSoundSourceList?.length ? '' : ' 无匹配数据'}`,
          title: '音源',
          options: evaluationDataSoundSourceList?.map(item=>{
            return {
              label: <Fragment>
                <Tag color="volcano" bordered={false}>{item.brand.title}</Tag>
                <Highlighter
                  highlightStyle={{
                    color: token.colorError,
                  }}
                  highlightTag="span"
                  searchWords={[searchValueRef.current!]}
                  textToHighlight={item.title}
                />
              </Fragment>,
              value: item.uuid,
            }
          }),
        },
      ]}
    />
}

export type ValueType = 'earbuds' | 'soundSource' | 'compose';
export interface Value{ uuid: string;type: ValueType }
